package com.yxp.offer;

import com.yxp.util.ListNode;

/**
 * @author : yang.xp
 * @date : 2021/8/23 9:13
 * @description : 剑指 Offer 18. 删除链表的节点
 */
public class Problem18 {

    public static void main(String[] args) {
        ListNode head = ListNode.initListNode(new int[]{4, 1, 5, 6});
        System.out.println(head.toString());
        Problem18 problem18 = new Problem18();
        ListNode resultNode = problem18.deleteNode(head, 6);
        System.out.println(resultNode.toString());
    }

    public ListNode deleteNode(ListNode head, int val) {
        ListNode preNode = head;
        if (preNode.val == val) {
            return head.next;
        }
        ListNode curNode = head.next;
        while (curNode != null) {
            if (curNode.val == val) {
                preNode.next = curNode.next;
                curNode.next = null;
                curNode = null;
            } else {
                preNode = curNode;
                curNode = curNode.next;
            }
        }
        return head;
    }
}
